// pages/listen/listen.js
var that,
  api = new(require('../../utils/api.js')),
  headimg = api.getimgurl(),
  headaudio = api.getaudiourl(),
  app = getApp(),
  util = new(require('../../utils/util.js'));
const myAudio = wx.getBackgroundAudioManager();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasphone:!1,
    swiperList: [{
      id: 0,
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big84000.jpg'
    }, {
      id: 1,
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big84001.jpg',
    }, {
      id: 2,
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big39000.jpg'
    }, {
      id: 3,
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big10001.jpg'
    }, {
      id: 4,
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big25011.jpg'
    }],
    navList: [{
      icon: '/pages/pic/bangdan.jpg',
      events: 'goToBangDan',
      color:'text-red',
      text: '绘本导读'
    },
    {
      icon: '/pages/pic/shoucang.jpg',
      events: 'tocollection',
      color: 'text-orange',
      text: '收藏'
    },
    {
      icon: '/pages/pic/hehuo.jpg',
      events: 'toHehuoren',
      color: 'text-yellow',
      text: '合伙人'
    }
  ],
    currentageindex: 0,
    checked: !1,
    nav: [
      '绘本',
      '故事',
      '国学',
      '英语',
      '儿歌',
      '哄睡',
      '音频',
    ],
    pageboxshow:!1,
    start: 0,
    pagesize: 20,
    stateicon: 'show',
    list: [],
    total: "",
    target: {},
    hasphone:!1,
    sendshow:!1,
    payshow:!1,
    parenting_price:''
    // swiper:[
    //   {
    //     imgs:[]
    //   }
    // ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    
    console.log(options,'optionsoptionsoptionsiddddd')
    let isgetphone=wx.getStorageSync('isgetphone'),type=wx.getStorageSync('type'),{parenting_price}=that.data
    if(isgetphone){
      that.setData({isgetphone,hasphone:!0,sendshow:!1,type})
    }
    that.setData({oid:options.id,navindex:options.navindex},()=>{
      that.getdata()
    })
  
    api.getsetting( res => {
      if (res.data.issuccess == 1) {
        parenting_price=res.data.data.parenting_price;
        that.setData({parenting_price})
        console.log(parenting_price)
      }
    });
  },
  inputchange(e){
    console.log(e,'eeeeeee')
    let {list}= that.data
    if(e.detail.value==''){
      that.setData({list:[]})
      that.getdata()
    }
  },
  swiperChange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  getPhoneNumber(e){
    let {hasphone,sendshow}=that.data
    api.getphone({edata:e.detail.encryptedData,iv:e.detail.iv},res=>{
      if(res.data.issuccess==1){
        let data = JSON.parse(res.data.data);
        let isgetphone=true
        wx.setStorageSync('isgetphone', isgetphone)
        that.setData({hasphone:!0,sendshow:!1,isgetphone})
        console.log(data,'data')
        //更新用户手机号
      }
    })
  },
  // 音频点赞
  audiofavor(e){
    let { id, data } = that.data, { isfavor } = data
    if (isfavor) {
      api.audiofavor( id , res => {
        if (res.data.issuccess == 1) {
          wx.showToast({
            title: '取消点赞',
            icon: 'none',
            duration: 1500
          })
          // isfavor= false
          data.isfavor= false 
          data.data.favor = data.data.favor - 1
          that.setData({ data })
        }
      })
    } else {
      api.audiofavor( id , res => {
        if (res.data.issuccess == 1) {
          wx.showToast({
            title: '点赞成功',
            icon: 'none',
            duration: 1500
          })
          data.isfavor = true 
          data.data.favor = data.data.favor+ 1
          that.setData({ data })
        }
      })
    }
  },
  toartice(e){
    console.log(111)
    let {
      item,
      index
    } = e.currentTarget.dataset || 0, {
      id,
      cid,
      audiosrc,
      src,
      orders
    } = item,{isgetphone,navindex}=that.data, type=wx.getStorageSync('type'),isnine=wx.getStorageSync('isnine')
    if(navindex==0){
      if(src==''){
        if(type=='VIP'){
          wx.navigateTo({
            url:'../rowdata/rowdata?id=' + id + '&index=' + index + '&cid=' + cid,
          })
        }else{
          if(orders!=89){
            wx.navigateTo({
              url:'../rowdata/rowdata?id=' + id + '&index=' + index + '&cid=' + cid,
            })
          }else{
              that.setData({sendshow:!0})
          }
      }
      }else{ 
        if(type=='VIP'){
          if (myAudio.src != audiosrc){
              wx.hideLoading()
              wx.navigateTo({
                url: '../artice/artice?id=' + id + '&index=' + index + '&cid=' + cid,
              })
            }else{
              wx.navigateTo({
                url: '../artice/artice?id=' + id + '&index=' + index + '&cid=' + cid + "&t=1",
              })
            }
        }else{
          if(orders!=89){
            if (myAudio.src != audiosrc){
            this.audioinit(item,()=>{
              wx.hideLoading()
              wx.navigateTo({
                url: '../artice/artice?id=' + id + '&index=' + index + '&cid=' + cid,
              })
            })
            }else{
              wx.navigateTo({
                url: '../artice/artice?id=' + id + '&index=' + index + '&cid=' + cid + "&t=1",
              })
            }
          }else{
            that.setData({sendshow:!0})
          }
      }
      }
  }else if(navindex==1){
    if(src==''){
      if(isnine=='1'){
        wx.navigateTo({
          url:'../rowdata/rowdata?id=' + id + '&index=' + index + '&cid=' + cid,
        })
      }else{
        if(orders!=89){
          wx.navigateTo({
            url:'../rowdata/rowdata?id=' + id + '&index=' + index + '&cid=' + cid,
          })
        }else{
            that.setData({payshow:!0})
        }
    }
    }else{ 
      if(isnine=='1'){
        if (myAudio.src != audiosrc){
            wx.hideLoading()
            wx.navigateTo({
              url: '../artice/artice?id=' + id + '&index=' + index + '&cid=' + cid,
            })
          }else{
            wx.navigateTo({
              url: '../artice/artice?id=' + id + '&index=' + index + '&cid=' + cid + "&t=1",
            })
          }
      }else{
        if(orders!=89){
          if (myAudio.src != audiosrc){
            wx.hideLoading()
            wx.navigateTo({
              url: '../artice/artice?id=' + id + '&index=' + index + '&cid=' + cid,
            })
          }else{
            wx.navigateTo({
              url: '../artice/artice?id=' + id + '&index=' + index + '&cid=' + cid + "&t=1",
            })
          }
        }else{
          that.setData({payshow:!0})
        }
    }
    }
  }else{
    if(src==''){
      wx.navigateTo({
        url:'../rowdata/rowdata?id=' + id + '&index=' + index + '&cid=' + cid,
      })
    }else{ 
      if (myAudio.src != audiosrc){
        wx.hideLoading()
        wx.navigateTo({
          url: '../artice/artice?id=' + id + '&index=' + index + '&cid=' + cid,
        })
      }else{
        wx.navigateTo({
          url: '../artice/artice?id=' + id + '&index=' + index + '&cid=' + cid + "&t=1",
        })
    }
    }
  }
  },
  todetail(e) {
    let {item, index} = e.currentTarget.dataset || 0, { id, cid,audiosrc,orders } = item,{isgetphone,navindex}=that.data, type=wx.getStorageSync('type');
      if(navindex==0){
      if(type!='VIP'){
        wx.showLoading({
          title: '加载中',
        })
        console.log(myAudio.src == audiosrc,'myAudio.src')
        if (myAudio.src != audiosrc){
          wx.hideLoading()
          wx.navigateTo({
            url: '../listendetail/listendetail?id=' + id + '&index=' + index + '&cid=' + cid,
          })
        }else{
          wx.navigateTo({
            url: '../listendetail/listendetail?id=' + id + '&index=' + index + '&cid=' + cid + "&t=1",
          })
        }
        console.log(e, 'e')
      }else{
        if(orders!=89){
          wx.showLoading({
            title: '加载中',
          })
      
          console.log(myAudio.src == audiosrc,'myAudio.src')
          if (myAudio.src != audiosrc){
            wx.hideLoading()
            wx.navigateTo({
              url: '../listendetail/listendetail?id=' + id + '&index=' + index + '&cid=' + cid,
            })
         
          }else{
            wx.navigateTo({
              url: '../listendetail/listendetail?id=' + id + '&index=' + index + '&cid=' + cid + "&t=1",
            })
          }
          console.log(e, 'e')
        }else{
          that.setData({sendshow:!0})
        }
      }
    }else{
      wx.showLoading({
        title: '加载中',
      })
      console.log(myAudio.src == audiosrc,'myAudio.src')
      if (myAudio.src != audiosrc){
  
        wx.hideLoading()
        wx.navigateTo({
          url: '../listendetail/listendetail?id=' + id + '&index=' + index + '&cid=' + cid,
        })
      // })
      }else{
        wx.navigateTo({
          url: '../listendetail/listendetail?id=' + id + '&index=' + index + '&cid=' + cid + "&t=1",
        })
      }
      console.log(e, 'e')
      }
  },
  no(){
    that.setData({sendshow:!1})
  },
  cancel(){
    that.setData({payshow:!1})
  },
  
  confirm(){
    let isnine=wx.getStorageSync('isnine'), openid =wx.getStorageSync('openid'),{parenting_price}=that.data,data = {openid,total:parenting_price};
 
    api.parentingpay(data,res => {
      if (res.succ == 1) {
        that.setData({payshow:!1})
        if(isnine=='0'){
          api.setnine(res =>{
            if(res.data.issuccess == 1){
            }
          })
        }
      } 
    })
  },
  
  formsubmit(e) {
    api.gatherformid(e, res => {
    })
  },

  audioinit(audio,succ){
    myAudio.stop();
    myAudio.src =audio.audiosrc;
    console.log(audio.audiosrc,'audiosrc');
    
    myAudio.title = audio.title;
    myAudio.play()
    myAudio.onCanplay(()=>{
      setTimeout(() => { succ && succ()},500)
    })
  },

  getnav(succ) {
    let itemlist = [];
    api.audiocatempgetlist(res => {
      if (res.data.issuccess == 1) {
        res.data.list.map((x, 
        i) => {
          itemlist.push(x);
        })
        console.log(itemlist,'navnav')
        that.setData({
          nav: itemlist
        }, () => {
          succ && succ()
        })
      }
    })
  },
  getlist() {
    let {
      start,
      pagesize,
      currentageindex,
      nav,
      list,oid
    } = that.data, cid = nav[currentageindex].id;
    api.audiogetlist({
      start,
      pagesize,
      cid:oid,
    }, res => {
      if (res.data.issuccess == 1) {
        that.formatlist((res.data.list), () => {
          console.log(list, 'list')
          that.setData({
            reachbtm: list.length == res.data.total,
             total: res.data.total
          },()=>{
            that.getpage()
          })
        })
      }

    })
  },

  

  getpage(){
    let { total, pagesize } = that.data, pagenumber, pageitem = [], left, right,item
    pagenumber = Math.ceil(total / pagesize)
    for (let i = 0; i < pagenumber;i++){
      if (i != pagenumber-1){
        left = i * pagesize + 1
        right = i * pagesize + pagesize
        item=left+'~'+right
        pageitem.push({ item })
      }else{
        left = i * pagesize + 1
        right = total
        if(left==right){
          item = left
        }else{
          item = left + '~' + right
        }
        pageitem.push({ item })
      }
    }
    that.setData({ pageitem })
  },
  itemstart(e){
    let { pagesize } = that.data,{ pageindex } = e.currentTarget.dataset
    that.setData({
      start: pageindex * pagesize, pageboxshow: !1, stateicon: 'show',list:[]
    }, () => {
      wx.pageScrollTo({
        selector: '.list',
        scrollTop: 0,
        duration: 0,
      })
      that.getlist()
    })
  },
  formatlist(getlist, reachbtm) {
    let {
      list
    } = that.data
    let newlist = getlist.map((x, i) => {
      x['imgsrc'] = headimg + x.thumbpath,
        x['audiosrc'] = headaudio + x.src;
      x['date']= util.formatDate(new Date(x.date));
      x.views = x.views >= 10000 ? (x.views / 10000).toFixed(1) + "万" : x.views
      return x;
    })
    let targetlist = list.concat(newlist);
    that.setData({
      list: targetlist
    }, () => {
      reachbtm()
    })

  },
  afterlogin: {
    token: res => {
      that.getdata();
    }
  },
  getdata() {
    let appletname=app.logininfo.appletname
    wx.setNavigationBarTitle({
      title: appletname  || '小巴学堂',
    })
    api.getcart(res=>{
      if(res.data.issuccess==1){
        app.badege(res.data.list);
      }
    })
    that.getnav(() => {
      that.getlist()
    })
    let {
      pagesize, cartids
    } = that.data;

    api.getmain(pagesize, res => {
      if (res.data.issuccess == 1) {
        let swiper = JSON.parse(util.decodeurl(res.data.data.swiper)),
          awards = res.data.data.awards,
          masters = res.data.data.masters,
          list = res.data.data.recommend,
          cart = res.data.data.cart,
          setting = res.data.data.settings;
        app.badege(cart);
        wx.setStorageSync("setting", setting);
        let target = {
            swiper,
            awards,
            masters
          }
       
        that.setData({ cartids})
        swiper.imgs.forEach((x, i) => {
          if (x.indexOf(headimg) == -1) {
            swiper.imgs[i] = headimg + x;
          }
        });
        awards.forEach((x, i) => {
          if (x.thumbpath.indexOf(headimg) == -1) {
            awards[i].thumbpath = headimg + x.thumbpath;
          }
        })
     
        console.log(swiper.imgs, 'getmain-start')
      
        that.setData(target)
      }
    });
  },
  listenbook() {
    let {
      checked
    } = this.data;
    checked = !checked;
    this.setData({
      checked
    });
  },
  chose(e) {
    wx.pageScrollTo({
      selector: '.list',
      scrollTop: 0,
      duration: 0,
    })

    let {
      currentageindex
    } = e.currentTarget.dataset, {
      nav
    } = this.data, cateindex = that.data.currentageindex;
    if (cateindex == currentageindex) return;
    /*获取可视窗口宽度*/
    　
    let w = wx.getSystemInfoSync().windowWidth,
      leng = nav.length,
      disX = (currentageindex - 1) * w / leng;
    this.setData({
      list: [],
      'navleft': disX,
      start: 0,
      cid: nav[currentageindex].id,
      currentageindex, pageboxshow: !1, stateicon: 'show',
      toview: 'item' + currentageindex
    }, () => {
      that.getlist()
    });
  },
  switchTab(event) {
    var currentageindex = event.detail.current;
    this.setData({
      currentageindex,
    });
  },

  isshow() {
    console.log(1111)
    if (that.data.pageboxshow == !1) {
      console.log(22222)
      that.setData({
        stateicon: 'hide',
        pageboxshow: !0
      })
    } else {
      console.log(333333)
      that.setData({
        stateicon: 'show',
        pageboxshow: !1
      })
    }
  },
  mod() {
    that.setData({
      stateicon: 'show',
      pageboxshow: !1
    })
  },
  // 搜索
  tosearch(e) {
    let keyword = e.detail.value,{oid}=that.data
    api.searchinclass({keyword,id:oid}, res => {
      if (res.data.issuccess == 1) {
        that.setData({
          list: []
        }, () => {
          console.log(res.data.list, 'res.data.list')
          that.formatlist(res.data.list, () => {
            that.setData({
            })
          })
        })
      }
    })
  },
  goToBangDan:function(){
    wx.navigateTo({
      url: '/pages/guideread/guideread',
    })
  },
  gotoSearch:function(){
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  tocollection() {
    wx.navigateTo({
      url: '../collection/collection',
    })
  },
  gotoHelp(){
    wx.navigateTo({
      url: '/pages/helps/helps',
    })
  },
  toHehuoren:function(){
    wx.navigateTo({
      url: '/pages/mine/hehuoren/hehuoren',
    })
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let isgetphone=wx.getStorageSync('isgetphone')
    if(isgetphone){
      that.setData({isgetphone,hasphone:!0,sendshow:!1})
    }
    wx.hideLoading();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    that.setData({
      start: 0,list:[]
    }, () => {
      that.getlist()
    })
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let {
      start, total
    } = this.data;
    if (start>total) {
      that.setData({ reachbtm:true})
  
      return
    }
    that.setData({
      start: that.data.start + that.data.pagesize
    }, () => {
      that.getlist()
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})